//
//  ZipUtil.m
//  HandPay
//
//  Created by xy on 10-3-23.
//  Copyright 2010 HANDPAY. All rights reserved.
//

#import "ZipUtil.h"
#import "Zlib.h"
#import "ZZTongDefine.h"

unsigned char * MYuncompress (desLen, source, sourceLen)
uLongf *desLen;
const Bytef *source;
uLong sourceLen;
{
	unsigned char dest[2000];
	unsigned char * destdata=NULL;
	uLongf destLen=2000;
    z_stream stream;
    int err,i;
	*desLen=0;
    stream.next_in = (Bytef*)source;
    stream.avail_in = (uInt)sourceLen;
    /* Check for source > 64K on 16-bit machine: */
    if ((uLong)stream.avail_in != sourceLen) return NULL;
	

	
    stream.zalloc = (alloc_func)0;
    stream.zfree = (free_func)0;
	stream.opaque=(voidpf)0;
	
    err = inflateInit2(&stream,-15);
    if (err != Z_OK) return NULL;
	
	while (true) {
		stream.next_out = dest;
		stream.avail_out = destLen;
		if ((uLong)stream.avail_out != destLen) return NULL;
		err = inflate(&stream, Z_NO_FLUSH);
		if (err==Z_STREAM_END || err==Z_OK) {
			unsigned char * tempdata=destdata;
			destdata=(unsigned char *)malloc(sizeof(unsigned char)*(stream.total_out));
			for (i=0; i<stream.total_out; i++) {
				if (i<*desLen && tempdata!=NULL) {
					destdata[i]=tempdata[i];
				}else {
					destdata[i]=dest[i-*desLen];
				}
			}
			if (tempdata!=NULL) {
				free(tempdata);
			}
			*desLen=stream.total_out;
			if (err==Z_STREAM_END) {
				break;
			}
		}else {
			if (destdata!=NULL) {
				free(destdata);
			}
			return NULL;
		}

	}
	
    err = inflateEnd(&stream);
    return destdata;
}

@implementation ZipUtil
+(NSData *)DepressData:(NSData *)scrdata;{
	NSData * redd=nil;
	uLongf slendd=[scrdata length];
	unsigned char * desdata=NULL;
	uLongf deslent=slendd*5;
	
	LOG(@"zippre: %ld",slendd);

	unsigned char * sourcdata=(unsigned char *) malloc(sizeof(unsigned char)*slendd);
	[scrdata getBytes:sourcdata];
	//sourcdata[slendd]='\0';

	//test_inflate(sourcdata, slendd,desdata,   600000);
	desdata=MYuncompress(&deslent,sourcdata, slendd);
	if (desdata!=NULL && deslent>0) {
		redd=[NSData dataWithBytes:desdata length:deslent];
		LOG(@"zipover: %ld",deslent);
	}
	if (desdata!=NULL) {
		free(desdata);
	}
	free(sourcdata);
	return redd;
}
@end
